import { forwardRef, useImperativeHandle, useState } from 'react';

import { useRequest } from 'ahooks';
import {
  Button,
  ColorPicker,
  Drawer,
  Form,
  FormProps,
  Input,
  InputNumber,
  Radio,
  Space
} from 'antd';

import IconSelect from '@/components/icon-select';

import { store } from '@/store';

import { noSpaceValidator } from '@/config/rule';
import { DictItemStatus, DictItemStatusObj } from '@/enum/dict';
import { dicInfoAdd, dicInfoUpdate } from '@/services/base/jichumokuaizidianxinxijiekou';

type EditItemOpenBaseArgs = {
  dicMain: BASE.DicMain;
  /** 成功回调 */
  onSuccess?: () => void;
};

export type EditItemRef = {
  open: (
    arg:
      | (EditItemOpenBaseArgs & {
          type: 'add';
        })
      | (EditItemOpenBaseArgs & {
          type: 'edit';
          rowData: BASE.DicInfoVO;
        })
      | (EditItemOpenBaseArgs & {
          type: 'detail';
          rowData: BASE.DicInfoVO;
        })
  ) => void;
};

export type EditItemProps = {};

const EditItem: React.ForwardRefRenderFunction<EditItemRef, EditItemProps> = (props, ref) => {
  const [form] = Form.useForm();
  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<EditItemRef['open']>[0]>();
  const submit = useRequest(
    async (values) => {
      const query = {
        ...values,
        mainId: args?.dicMain.id
      };

      if (args?.type === 'edit' && args.rowData) {
        query.id = args.rowData.id;
      }

      await (args?.type === 'edit' ? dicInfoUpdate(query) : dicInfoAdd(query));

      args?.onSuccess?.();
      setOpen(false);

      store.app?.message.success(args?.type === 'edit' ? '编辑成功' : '新增成功');
    },
    {
      manual: true
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (args) => {
        setArgs(args);
        setOpen(true);

        setTimeout(() => {
          // 编辑回填数据
          if ((args?.type === 'edit' || args?.type === 'detail') && args?.rowData) {
            // 回填数据
            form.setFieldsValue(args.rowData);
          } else {
            form.resetFields();
            form.setFieldsValue({
              // 状态
              dicStatus: DictItemStatus.启用
            });
          }
        });
      }
    };
  });

  const onFinish: FormProps['onFinish'] = async (values) => {
    return submit.runAsync(values);
  };

  const onCancel = () => {
    if (submit.loading) {
      store.app?.message.info('正在提交中，请稍后');

      return;
    }

    setOpen(false);
  };

  return (
    <Drawer
      title={
        {
          add: '新增字典项',
          edit: '编辑字典项',
          detail: '字典项详情'
        }[args?.type as string]
      }
      extra={
        <Space>
          <Button
            type="primary"
            loading={submit.loading}
            disabled={submit.loading}
            onClick={form.submit}
          >
            保存
          </Button>
          <Button onClick={onCancel} disabled={submit.loading}>
            取消
          </Button>
        </Space>
      }
      width="50%"
      open={open}
      onClose={onCancel}
    >
      <Form
        onFinish={onFinish}
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        initialValues={{}}
        requiredMark={args?.type !== 'detail'}
        variant={args?.type === 'detail' ? 'borderless' : undefined}
      >
        <Form.Item
          label="字典项名称"
          name="dicName"
          rules={[
            { required: true, message: '请填写字典项名称' },
            {
              validator: noSpaceValidator
            },
            {
              validator: async (_, value) => {
                // 不对空值校验
                if (value === '' || value === null || typeof value === 'undefined') {
                  return;
                }

                const max = 200;

                if (String(value).length > max) {
                  throw new Error(`最多只能输入${max}个字符`);
                }
              }
            }
          ]}
        >
          <Input placeholder="请输入字典项名称" />
        </Form.Item>

        <Form.Item
          label="字典值"
          name="dicValue"
          rules={[
            { required: true, message: '请填写字典值' },
            {
              validator: noSpaceValidator
            }
          ]}
        >
          <Input placeholder="请输入字典值" />
        </Form.Item>

        <Form.Item
          label="状态"
          name="dicStatus"
          rules={[{ required: true, message: '请选择状态' }]}
        >
          <Radio.Group>
            {Array.from(DictItemStatusObj).map(([value, label]) => (
              <Radio value={value} key={value}>
                {label.text}
              </Radio>
            ))}
          </Radio.Group>
        </Form.Item>

        <Form.Item label="字典颜色" name="dicColour" getValueFromEvent={(_, e) => e}>
          <ColorPicker />
        </Form.Item>

        <Form.Item label="字典图标" name="dicIcon">
          {/* // TODO: 字典图标上传 */}
          <IconSelect allowClear />
        </Form.Item>

        <Form.Item label="排序" name="dicSort">
          <InputNumber step={1} />
        </Form.Item>

        <Form.Item label="说明" name="dicExplain">
          <Input.TextArea placeholder="请输入说明" />
        </Form.Item>
      </Form>
    </Drawer>
  );
};

export default forwardRef(EditItem);
